#include "uda1341.h"

#define L2DATA  PE5
#define L2MODE  PC7
#define L2CLK  PC6

void delaylong(){
	for(uint16_t i = 0;i < 1500;i++){
		
	}
}
void delayshort(){
	for(uint16_t i = 0;i < 500;i++){
		
	}
}

int read_data(int8_t addr){
	delaylong();	
	delaylong();
	delaylong();
	delaylong();
	delaylong();
	GPIO_SetMode(PC,BIT6,GPIO_PMD_OUTPUT);
	GPIO_SetMode(PC,BIT7,GPIO_PMD_OUTPUT);
	GPIO_SetMode(PE,BIT5,GPIO_PMD_OUTPUT);
	delayshort();
	L2CLK = 1;
	L2MODE = 0;
	L2DATA = 1;
	delaylong();
	
	int8_t ret = 0;
	for(int i = 0; i < 8;i++){
		L2CLK = 0;
		L2DATA = (((0x01<<i)&addr) > 0)?1:0;
		delayshort();
		
		L2CLK = 1;
		delayshort();
	}
	L2CLK = 0;
	L2MODE = 1;
	delayshort();
	L2MODE = 0;
	delayshort();
	L2MODE = 1;
	GPIO_SetMode(PE,BIT5,GPIO_PMD_INPUT);
	delaylong();

	for(int i = 0; i < 8;i++){
		L2CLK = 0;
		delayshort();
		if(L2DATA == 1)
			ret += (0x01<<i);
		L2CLK = 1;
		delayshort();
	}
	L2CLK = 0;

	return ret;
}



int set_data(int8_t addr,int8_t data){
	delaylong();	
	delaylong();
	delaylong();
	delaylong();
	delaylong();
	GPIO_SetMode(PC,BIT6,GPIO_PMD_OUTPUT);
	GPIO_SetMode(PC,BIT7,GPIO_PMD_OUTPUT);
	GPIO_SetMode(PE,BIT5,GPIO_PMD_OUTPUT);
	delayshort();
	L2CLK = 1;
	L2MODE = 0;
	L2DATA = 1;
	delaylong();
	
	int8_t ret = 0;
	for(int i = 0; i < 8;i++){
		L2CLK = 0;
		L2DATA = (((0x01<<i)&addr) > 0)?1:0;
		delayshort();
		L2CLK = 1;
		delayshort();
	}
	L2CLK = 0;
	L2MODE = 1;
	delayshort();
	L2MODE = 0;
	delayshort();
	L2MODE = 1;
	delayshort();

	for(int i = 0; i < 8;i++){
		L2CLK = 0;
		delayshort();
		L2DATA = (((0x01<<i)&data) > 0)?1:0;
		delayshort();
		
		L2CLK = 1;
		delayshort();
	}
	L2CLK = 0;

	return ret;
}